
#include "LPC23xx.h"
#include "io.h"
#include "isd.h"
#include "macros.h"
#include "debug.h"


/* #define   SPI_OUT				PORT_0_PIN.PIN_9		 */
/* #define   SPI_OUT_DIR		PORT_0_DIR.PIN_9	 */
											
/* #define   SPI_INP				PORT_0_PIN.PIN_8				 */
/* #define   SPI_INP_DIR		PORT_0_DIR.PIN_8	 */
											
/* #define   SPI_CLK				PORT_0_PIN.PIN_7		 */
/* #define   SPI_CLK_DIR		PORT_0_DIR.PIN_7	 */
											
/* #define   SPI_CS				PORT_0_PIN.PIN_6	 */
/* #define   SPI_CS_DIR			PORT_0_DIR.PIN_6	 	 */


/* #define   PIN_ISD_INT		PORT_0_PIN.PIN_5 */
/* #define   PIN_ISD_INT_DIR	PORT_0_DIR.PIN_5 */



#define   SPI_OUT				PORT_0_PIN.PIN_18		
#define   SPI_OUT_DIR		PORT_0_DIR.PIN_18
											
#define   SPI_INP				PORT_0_PIN.PIN_16				
#define   SPI_INP_DIR		PORT_0_DIR.PIN_16	
											
#define   SPI_CLK				PORT_0_PIN.PIN_15		
#define   SPI_CLK_DIR		PORT_0_DIR.PIN_15
											
#define   SPI_CS				PORT_0_PIN.PIN_19	
#define   SPI_CS_DIR			PORT_0_DIR.PIN_19 	


#define   PIN_ISD_INT		PORT_0_PIN.PIN_20
#define   PIN_ISD_INT_DIR	PORT_0_DIR.PIN_20


#define   PIN_DEBOUNCE		100	

#define spi_delay() NOP();NOP();NOP();NOP()


void isd_init( void )
{
	SPI_INP_DIR = PIN_INPUT;

	SPI_CS = 1;
	SPI_CS_DIR = PIN_OUTPUT;

	SPI_CLK = 0;
	SPI_CLK_DIR = PIN_OUTPUT;

	SPI_OUT = 0;
	SPI_OUT_DIR = PIN_OUTPUT;


	PIN_ISD_INT_DIR = PIN_INPUT;

}
 
static unsigned int isd_spi( unsigned int cmd )	
{
	unsigned int i, rec = 0;
		
	SPI_CS = 0;
	spi_delay();

	for ( i = 0; i < 16; i++ )
	{
		if ( cmd & 0x01 )
		{
			SPI_OUT = 1;
		}
		else
		{
			SPI_OUT = 0;
		}
		spi_delay();

		SPI_CLK = 1;
		spi_delay();

		cmd >>= 1;
		
		SPI_CLK = 0;
		spi_delay();
		
		rec >>= 1;
		
		rec |= (unsigned int)SPI_INP << 15;
	}

	SPI_CS = 1;
	spi_delay();

	return rec;
}

unsigned int isd_cmd ( unsigned int addr, unsigned int ctrl )
{
	unsigned int cmd = addr;
	cmd |= ctrl<<11; 

	return isd_spi(cmd);
}

unsigned int pin_isd_INT_state;
unsigned int pin_isd_INT_filter;
unsigned int pin_isd_INT_event;

unsigned int isd_message_status;


void isd_driver ( void )
{
	isd_message_status = 0;

	if ( pin_isd_INT_state == PIN_STATE_LO )
	{
		if ( PIN_ISD_INT )
		{
			if ( ++pin_isd_INT_filter >= PIN_DEBOUNCE )
			{
				pin_isd_INT_state = PIN_STATE_HI;
				pin_isd_INT_filter = 0;
				pin_isd_INT_event = PIN_EVENT__UP;
					
			}
		}
		else
		{
			pin_isd_INT_filter = 0;
		}
	}
	else
	{
		if ( !PIN_ISD_INT )
		{
			if ( ++pin_isd_INT_filter >= PIN_DEBOUNCE )
			{
				pin_isd_INT_state = PIN_STATE_LO;
				pin_isd_INT_filter = 0;
				pin_isd_INT_event = PIN_EVENT__DOWN;
			}
		}
		else
		{
			pin_isd_INT_filter = 0;
		}
	}	

	if ( 	pin_isd_INT_event != PIN_EVENT__DOWN )
		return;

	pin_isd_INT_event = PIN_EVENT__NO;

	isd_message_status = ISD_MSG_EOM;

	DBG("\n%s; === ISD EOM ===\n",__FUNCTION__); 
}



























/* void isd_put_cmd( unsigned char* s ) */
/* { */
/* 	while( *s ) */
/* 	{ */
/* 		isd_putch(*s++); */
/* 	} */
/* } */
